package cn.glutnn.controller;


import cn.glutnn.entity.Messages;
import cn.glutnn.entity.Result;
import cn.glutnn.entity.dto.MessageDTO;
import cn.glutnn.service.MessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * (Messages)表控制层
 *
 * @author msh
 * @since 2024-12-27 13:06:42
 */
@RestController
@RequestMapping("/messages")
public class MessagesController {
    @Autowired
    private MessagesService messagesService;

    // 获取所有消息（发送或接收）
    @GetMapping("/{userId}")
    public Result<List<MessageDTO>> getAllMessages(@PathVariable int userId) {
        return messagesService.getMessages(userId);
    }

    // 获取未读消息
    @GetMapping("/unread/{receiverId}")
    public Result<List<Messages>> getUnreadMessages(@PathVariable int receiverId) {
        return messagesService.receiveUnreadMessages(receiverId);
    }

    // 发送消息
    @PostMapping("/send")
    public Result<String> sendMessage(@RequestBody Messages message) throws IOException {
        message.setCreatedTime(new Date());
        message.setStatus(0); // 未读状态
        messagesService.sendMessage(message);
        
        return Result.success("发送成功");
    }

    // 获取与某个用户商家的聊天记录
    @GetMapping("/history")
    public Result<List<Messages>> getChatHistory(
        @RequestParam Integer senderId,
        @RequestParam Integer receiverId
    ) {
        return messagesService.getMessagesBySenderIdAndReceiverId(senderId, receiverId);
    }

    // 标记消息已读
    @PutMapping("/read/{senderId}")
    public Result<String> markMessageAsRead(@PathVariable Integer senderId) {
        messagesService.markAsRead(senderId);
        return Result.success("修改成功");
    }
}

